package com.zh.work.util.jy;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author liujinlei
 * @version 2.0
 * @description MD5工具类
 * @date 2019/9/3 10:08
 */
public class JYMD5 {
	
	/**
     * base64字符替换
     */
    private static final String BASE64_CHAR_ADD = "+";
    private static final String BASE64_CHAR_REDUCE = "-";
    private static final String BASE64_CHAR_DIVIDE = "/";
    private static final String BASE64_CHAR_UNDERLINE = "_";
    /**
     * md5
     * s:需要md5的字符串
     * charset:编码格式
     */
    public final static String MD5Encoder(String s, String charset) {
        try {
            byte[] btInput = s.getBytes(charset);
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < md.length; i++) {
                int val = ((int) md[i]) & 0xff;
                if (val < 16) {
                    sb.append("0");
                }
                sb.append(Integer.toHexString(val));
            }
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * md5
     * s:需要md5的字符串
     * 默认编码格式：UTF-8
     */
    public static String MD5Encoder(String s) {
        return MD5Encoder(s, "utf-8");
    }

    /**
     * 参数排序后拼接为字符串
     * obj:需要排序拼接的对象
     */
    public static String getSortJsonStr(JSONObject obj) {
        if (obj!=null){
            obj.remove("cutFlag");
        }
        List<String> keys = obj.keySet().stream().sorted().collect(Collectors.toList());
        Optional<String> reduce = keys.stream().filter(s -> StringUtils.isNotEmpty(obj.getString(s))).map(s -> s + "=" + obj.getString(s)).reduce((str, f) -> str + "," + f);
        //判断optonal是否为空，防止NoSuchElementException异常
        if (reduce != null && reduce.isPresent()) {
            return reduce.get();
        }
        return "";
    }
    
    /*
     * 获取签名sign方法
     */

    public static String createSignature(JSONObject jsb, String appSecret) {
    	 if (jsb == null || jsb.isEmpty()) return null;

         jsb.remove("sign");
         String bizContentStr = "";

         if (StringUtils.isNotEmpty(jsb.getString("biz_content"))) {
             bizContentStr = JYMD5.getSortJsonStr(jsb.getJSONObject("biz_content"));
         }
         jsb.remove("biz_content");
         String dtoStr = JYMD5.getSortJsonStr(jsb) + "," + bizContentStr;
         String result = JYMD5.MD5Encoder(dtoStr + appSecret, "UTF-8");
         //System.out.printf("加密串--->{}", result);

         return result;
     }
    

    /**
     * 视频、照片base64中的+替换为-， /替换为_
     *
     * @param base64
     * @return
     */
    public static String encrypt(String base64) {
        if (StringUtils.isEmpty(base64)) {
            return null;
        }
        return base64.replace(BASE64_CHAR_ADD, BASE64_CHAR_REDUCE).replace(BASE64_CHAR_DIVIDE, BASE64_CHAR_UNDERLINE);
    }

    /**
     * 视频、照片base64中的 - 替换为 +， _ 替换为 /
     *
     * @param base64
     * @return
     */
    public static String decrypt(String base64) {
        if (StringUtils.isEmpty(base64)) {
            return null;
        }
        return base64.replace(BASE64_CHAR_REDUCE, BASE64_CHAR_ADD).replace(BASE64_CHAR_UNDERLINE, BASE64_CHAR_DIVIDE);
    }

    
    
}
